/**
 * HttpResponse.java
 * 
 * Create Version: 1.0
 * Author: 刘洪政
 * Create Date: 2012-4-23
 */
package ysyh55.android.base.http;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import ysyh55.android.base.exception.HttpResponseException;

/**
 * HttpResponse Http 服务器反馈封装类
 * 
 * @author 刘洪政
 */
public class HttpResponse {
	private static final String TAG = "http.Response";
	private final org.apache.http.HttpResponse response;

	public HttpResponse(org.apache.http.HttpResponse response) {
		this.response = response;
	}

	public long getContentLength() {
		return response.getEntity().getContentLength();
	}

	public InputStream asStream() throws IOException, HttpResponseException {
		HttpEntity entity = response.getEntity();
		try {
			return entity.getContent();
		} catch (IllegalStateException e) {
			Log.d(TAG, e.getMessage(), e);
			throw new HttpResponseException(e.getMessage(), e);
		}
	}

	public String asString() throws HttpResponseException, IOException {
		try {
			return EntityUtils.toString(response.getEntity());
		} catch (ParseException e) {
			Log.d(TAG, e.getMessage(), e);
			throw new HttpResponseException(e.getMessage(), e);
		}
	}

	public JSONObject asJSONObject() throws HttpResponseException, IOException {
		try {
			return new JSONObject(asString());
		} catch (JSONException e) {
			Log.d(TAG, e.getMessage(), e);
			throw new HttpResponseException(e.getMessage(), e);
		}
	}

	public JSONArray asJSONArray() throws HttpResponseException, IOException {
		try {
			return new JSONArray(asString());
		} catch (JSONException e) {
			Log.d(TAG, e.getMessage(), e);
			throw new HttpResponseException(e.getMessage(), e);
		}
	}
}
